#!/usr/bin/env node

/**
 * Created by tdzl2003 on 7/19/16.
 */

const request = require('request');
const path = require('path');
const fs = require('fs');
const argv = require('cli-arguments').parse(require('./cli.json'));
const options = argv.options;
const mime = require('mime');

function uploadFile(fn, options, exts) {
  const formData = {
    key: options.key,
    token: options.token,
    file: {
      value:  fs.createReadStream(fn),
      options: {
        filename: path.basename(fn),
        contentType: mime.lookup(fn),
      },
    },
  };
  if (exts) {
    for (k in exts) {
      formData[`x:${k}`] = exts[k];
    }
  }
  request.post(options.upload_url, {
    formData,
  }, function (error, response, body) {
    if (error) {
      console.log(error);
      return;
    }
    console.log(body);
  });
}

request.post('http://api.fir.im/apps', {
  body: {
    type: options.type,
    bundle_id: options['bundle-id'],
    api_token: options['api-token'],
  },
  json: true,
}, function (error, response, body) {
  if (error){
    console.log(error);
    return;
  }
  console.log(body);
  if (body.code) {
    return;
  }

  if (options.icon) {
    uploadFile(options.icon, body.cert.icon);
  }
  if (options.binary) {
    uploadFile(options.binary, body.cert.binary);
  }
});
